<?php


function getShortByLong($sUrl) {
	$sql = sprintf("SELECT * FROM us__urls WHERE url_long = '%s' LIMIT 1",
		mysql_real_escape_string($sUrl));

	$resource = mysql_query($sql);
	if ($resource) {
		$row = mysql_fetch_assoc($resource);
		if ($row)
			return $row;
	}

	return false;
}

function getLongByShort($sUrl) {
	$sql = sprintf("SELECT * FROM us__urls WHERE url_short = '%s' LIMIT 1",
		mysql_real_escape_string($sUrl));

	$resource = mysql_query($sql);
	if ($resource) {
		$row = mysql_fetch_assoc($resource);
		if ($row)
			return $row['url_long'];
	}

	return false;
}


function generateShortUrl($sLongUrl) {
//	$sShort = md5($sLongUrl);

	/*$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$base = strlen($codeset);
	$n = 300;
	$converted = "";

	while ($n > 0) {
		$converted = substr($codeset, ($n % $base), 1) . $converted;
		$n = floor($n/$base);
	}*/

	$sShortUrl = uniqid('!');

	return $sShortUrl;
}





function addUrl($sLongUrl, $sShortUrl) {
	$sql = sprintf("INSERT INTO us__urls (`url_long`, `url_short`) VALUES ('%s', '%s')",
		$sLongUrl, $sShortUrl);
	$resource = mysql_query($sql);
	if ($resource)
		return true;

	return false;
}

function getTotalUrls() {
	$resource = mysql_query('SELECT count(*) FROM us__urls');
	if ($resource) {
		$row = mysql_fetch_row($resource);
		$counter = $row[0]; // количество сокращенных url
	}

	return $counter;
}


function getAllUrls() {
	$resource = mysql_query('SELECT * FROM us__urls');
	if ($resource) {
		while ($row = mysql_fetch_assoc($resource)){
			$rows[] = $row;
		};
		return $rows;
	}
	return false;
}

function getLastUrls($iLimit = 3) {
	$sql = "SELECT * FROM us__urls ORDER BY id DESC LIMIT {$iLimit}";
	$resource = mysql_query($sql);
	$rows = array();
	if ($resource)
		while ($row = mysql_fetch_assoc($resource))
			$rows[] = $row;

	return $rows;
}